import { defineEventHandler, readBody, createError } from 'h3';
import { getDbConnection } from '../../utils/db.js';
import { requireUser } from '../../utils/auth.js';

export default defineEventHandler(async (event) => {
  try {
    const { userId } = requireUser(event);

    const { noteId, name, content, changeSummary, icon, iconColor } = await readBody(event);

    const db = await getDbConnection();
    
    // 获取当前笔记信息用于版本记录
    const currentNote = await db.get(
      'SELECT name, content FROM notes WHERE id = ? AND user_id = ?',
      [noteId, userId]
    );
    
    if (!currentNote) {
      throw createError({ statusCode: 404, statusMessage: 'Note not found' });
    }
    
    // 只有内容或标题发生变化时才创建版本
    if (currentNote.name !== name || currentNote.content !== content) {
      // 获取下一个版本号
      const lastVersion = await db.get(
        'SELECT MAX(version_number) as last_version FROM note_versions WHERE note_id = ?',
        [noteId]
      );
      
      const nextVersion = (lastVersion?.last_version || 0) + 1;
      
      // 保存当前版本到历史表
      await db.run(
        `INSERT INTO note_versions (note_id, name, content, version_number, change_summary) 
         VALUES (?, ?, ?, ?, ?)`,
        [noteId, currentNote.name, currentNote.content, nextVersion, changeSummary || null]
      );
    }
    
    // 更新笔记
    await db.run(
      `UPDATE notes 
       SET name = ?, content = ?, icon = ?, iconColor = ?, updated_at = CURRENT_TIMESTAMP 
       WHERE id = ? 
         AND user_id = ?`,
      [name, content, icon || null, iconColor || null, noteId, userId]
    );

    return { success: true, versionCreated: currentNote.name !== name || currentNote.content !== content };
  } catch (error) {
    console.error('Error saving note:', error);
    throw createError({ statusCode: 500, statusMessage: 'Failed to save note' });
  }
});
